(function (window, $, undefined) {
  'use strict';

  var dictData = {
    cityId: {},
    status: {},
    licenseState: {
      '0': '有效',
      '1': '失效'
    }
  };

  var supplierData = {};

  main(function () {

    var $tableSupplier = $('#table-supplier');
    util.jqGrid($tableSupplier, {
      url: ajaxURL.ORGANIZATION + '/supplier/getSupplierList',
      datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { name: 'kid', key: true, hidden: true },
        {
          label: '城市', name: 'cityId', width: 50, formatter: function (v, o, r) {
            return dictData.cityId[v] || '';
          }
        },
        {
          label: '车辆供应商名称', name: 'name', width: 150, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.kid + '">' + v + '</a>';
          }
        },
        { label: '公司ID', name: 'supplierNo', width: 80 },
        {
          label: '状态', name: 'status', width: 80, formatter: function (v, o, r) {
            return dictData.status[v] || '';
          }
        },
        { label: '联系人', name: 'contact', width: 100 },
        { label: '联系人电话', name: 'contactPhone', width: 100 },
        { label: '许可证号', name: 'licenseId', width: 120 },
        // { label: '提供车辆类类型', name: '', width: 120 },
        {
          label: '录入时间', name: 'createTime', width: 100, formatter: function (v, o, r) {
            return util.getDate(v);
          }
        },
        // { label: '操作记录', name: '', width: 120 }
      ],
      loadComplete: function (res) {
        supplierData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            supplierData[item.kid] = item;
          });
        }
      },
      pager: '#pager-supplier'
    });

    // 获取城市列表
    util.ajax(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', '', 'GET', util.resCallback(function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        dictData.cityId[item.cityId] = item.name;
      });
      searchTable();
    }));

    util.getDict('status', 'status').then(function (data) {
      util.selectHtml('[name="status"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.status[item.value] = item.name;
      });
    });

    // util.getDict('licenseState', 'licenseState').then(function (data) {
    //   util.selectHtml('[name="licenseState"]', data, 'value', 'name', '请选择');
    //   $.each(data, function (_, item) {
    //     dictData.licenseState[item.value] = item.name;
    //   });
    // });

    var $searchCondition = $('.search-condition');

    // 表单搜索功能
    $('#btn-search').click(function () {
      var data = util.formData($searchCondition)

      $tableSupplier.jqGrid('setGridParam', {  // 重新加载数据
        postData: data,
        page: 1
      }).trigger("reloadGrid");
    })

    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableSupplier, data);
    }

    $('btn-search').click(searchTable);

    var $layerSupplier = $('#layer-supplier-detail');
    var $formSupplier = $('#form-supplier-detail');

    // 录入时间
    laydate.render({
      elem: '#createDate' //指定元素
    });

    // 初次发证日期
    laydate.render({
      elem: '#getLicenseDate'
    })

    // 有效期
    laydate.render({
      range: '至',
      elem: '#licensePeriod',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#licensePeriod').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    laydate.render({
      range: '至',
      elem: '#licensePeriod',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#licensePeriod').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 新增操作
    $('#btn-add').click(function () {
      $layerSupplier.find(':input').removeAttr('disabled');
      util.resetForm($formSupplier);
      util.layerOpen({
        // title: '车辆供应管理 - 新增',
        title: false,
        content: $layerSupplier,
        area: ['1000px', ''],
        btn: ['确定新增', '取消'],
        yes: function () {
          supplierSave()
        },
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // 查看供应商
    $tableSupplier.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');
      // 根据 id 请求数据

      $layerSupplier.find(':input').removeAttr('placeholder');
      var data = supplierData[id];

      data.getLicenseDate = util.getDate(data.getLicenseDate);
      data.licensePeriod = util.getDate(data.licenseOn) + ' 至 ' + util.getDate(data.licenseOff);

      util.fillForm($layerSupplier, data);

      util.layerOpen({
        // title: '平台车辆管理 - 详情',
        title: false,
        content: $layerSupplier,
        area: ['1000px', '']
      });
    });

    // 修改供应商
    $('#btn-edit').click(util.oneCheck($tableSupplier, function (id) {
      $formSupplier.find(':input').removeAttr('disabled');
      var data = supplierData[id];
      data.getLicenseDate = util.getDate(data.getLicenseDate);
      data.licensePeriod = util.getDate(data.licenseOn) + ' 至 ' + util.getDate(data.licenseOff);
      util.fillForm($formSupplier, data);
      util.layerOpen({
        // title: '平台车辆管理 - 修改',
        title: false,
        content: $layerSupplier,
        area: ['1000px', ''],
        btn: ['确认修改', '取消'],
        yes: function () {
          supplierSave()
        },
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    }));


    // 停用人力服务公司
    $('#btn-block').click(util.oneCheck($tableSupplier, function (id) {
      layer.confirm('确定停用该人力服务公司？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('停用操作...');
      });
    }));

    // 启用人力服务公司
    $('#btn-use').click(util.oneCheck($tableSupplier, function (id) {
      layer.confirm('确定启用该人力服务公司？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('启用操作...');
      });
    }));

    // 导出
    $('#btn-export').click(function () {
      util.tip.warn('导出操作...');
    });

    // 导入
    $('#btn-import').click(function () {
      util.tip.warn('导出操作...');
    });

    var $validate = $formSupplier.validate({
      rules: {
        cityId: { required: true },
        name: { required: true, maxlength: 20 },
        supplierNo: { required: true },
        address: { required: true, maxlength: 100 },
        licenseId: { required: true, maxlength: 20 },
        businessArea: { required: true, maxlength: 100 },
        census: { required: true, maxlength: 20 },
        licensePeriod: { required: true },
        getLicenseDate: { required: true },
        licenseState: { required: true },
        contact: { required: true, maxlength: 20 },
        contactPhone: { required: true },
        remark: { maxlength: 200 }
      },
      messages: {
        cityId: { required: '请选择城市' },
        name: { required: '请输入供应商名称' },
        supplierNo: { required: '请输入公司ID' },
        address: { required: '请输入详细地址' },
        licenseId: { required: '请输入许可证号' },
        businessArea: { required: '请输入经营区域' },
        census: { required: '请输入发证机构名称' },
        licensePeriod: { required: '请选择有效期' },
        getLicenseDate: { required: '请选择初次发证日期' },
        licenseState: { required: '请选择证照状态' },
        contact: { required: '请输入联系人' },
        contactPhone: { required: '请输入联系人手机号' }

      },
      errorPlacement: function (error, element) { //错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      }
    });

    function supplierSave() {
      var data = util.formData($formSupplier);
      util.toTimeStamp(data, [
        'getLicenseDate',
        'licenseOn',
        'licenseOff'
      ])
      data.addressCityId = data.cityId;
      if ($validate.form()) {
        // data.kid 来决定是什么操作，有为修改，无为新增
        var url = ajaxURL.ORGANIZATION + (data.kid ? '/supplier/updateSupplier' : '/supplier/addSupplier');
        util.ajax(url, JSON.stringify(data), 'POST', util.resCallback(function (res) {
          layer.closeAll();
          util.tip.success('操作成功');
          $tableSupplier.trigger('reloadGrid');
        }));
      }
    }

  });
})(window, jQuery);
